from mailmerge import MailMerge
import logzero
import os


def generateDocByTemplate(data, templatePath, outputPath, logger=logzero.logger):
    if not os.path.isfile(templatePath):
        logger.error("template is not a file {}".format(templatePath))
        return False
    try:
        document_1 = MailMerge(templatePath)
        logger.info(document_1.get_merge_fields())
        document_1.merge(**data)
        document_1.write(outputPath)
    except FileNotFoundError:
        logger.error("template file not found {} -> {}".format(templatePath, outputPath))
        return False
    except PermissionError:
        logger.error("output file PermissionError {}".format(outputPath))
        return False
    except KeyError:
        logger.error("maybe template file problem {}".format(templatePath))
        return False
    except Exception:
        logger.exception("convert doc failed by {} and {} to {}".format(templatePath, data, outputPath))
        return False
    else:
        logger.info("generate success {} {}".format(data, outputPath))
        return True
    finally:
        document_1.close()


"""
templatePath = 'CSPAC206MTemp.docx'
outputPath = 'test-otput.docx'

data = dict(
    check_date='2018-12-13',
    check_name='小明',
    fq_02='50.00',
    fq_10='49.99',
    i0_02='0.19',
    i0_05='0.50',
    i0_10='1.01',
    i0_15='1.51',
    ia_02='0.22',
    ia_05='0.52',
    ia_10='1.02',
    ia_15='1.52',
    ib_02='0.23',
    ib_05='0.53',
    ib_10='1.03',
    ib_15='1.53',
    ic_02='0.24',
    ic_05='0.54',
    ic_10='1.04',
    ic_15='1.54',
    ilk_02='0.25',
    ilk_05='0.55',
    ilk_10='1.05',
    ilk_15='1.55',
    p_02='44.2',
    p_10='220.1',
    pf_02='0.502',
    pf_10='0.499',
    q_02='19.2',
    q_10='19.5',
    uab_02='44.01',
    uab_10='220.01',
    uab_12='264.5',
    ubc_02='44.02',
    ubc_10='220.02',
    ubc_12='264.2',
    uca_02='44.03',
    uca_10='220.03',
    uca_12='264.3',
)
generateDocByTemplate(data, templatePath, outputName)
"""
